package app.controllers.member;

import app.Const;
import app.kit.TypeKit;
import app.models.basic.Dict;
import app.models.basic.RiskModel;
import app.models.basic.RiskOptions;
import app.models.basic.RiskProblem;
import app.models.member.Member;
import com.google.common.base.Strings;
import com.google.common.primitives.Ints;
import goja.StringPool;
import goja.mvc.AjaxMessage;
import goja.mvc.Controller;
import goja.security.goja.SecurityKit;

import java.util.List;

/**
 * Created by user on 2015/3/19.
 *
 */
public class QuestionnaireController extends Controller {
    /*
    调整风险评估页
     */
    public void index(){
        Member member = SecurityKit.getLoginUser(getRequest());
        member = member.findbyPhone(member.getStr("phone"));
        List<RiskProblem> riskProblems = RiskProblem.dao.findAll();
        for(RiskProblem riskProblem:riskProblems){
            List<RiskOptions> optionses = RiskOptions.dao.findByProblem(riskProblem.getBigDecimal("id").intValue());
            riskProblem.set("options",optionses);
        }
        setAttr(Const.FIELD_RISK_TOLERANCE,member.get(Const.FIELD_RISK_TOLERANCE)+"");
        setAttr("result",riskProblems);
        final String redirect_url = getPara("redirect_url");
        if (!Strings.isNullOrEmpty(redirect_url)) {
            setAttr("redirect_url", redirect_url);
        }
        String retry = getPara("retry");
        if(!Strings.isNullOrEmpty(retry)){
            setAttr("retry", retry);
        }
    }

    /*
    处理答题结果
     */
    public void answer(){
        String options = getPara("answer");
        List<RiskProblem> riskProblems = RiskProblem.dao.findAll();
        String[] result = options.split(",");
        if(result.length<riskProblems.size()){
            renderAjaxFailure("还有"+(riskProblems.size()-result.length)+"题未答");
        }
        int socre = 0;
        if(result.length==riskProblems.size()){
            for(String s:result){
                RiskOptions o = RiskOptions.dao.findById(s);
                int a = TypeKit.getInt(o, "score");
                socre = a+socre;
            }
            String riskLevel = RiskModel.dao.findRisk_level(socre);
            Member member = SecurityKit.getLoginUser(getRequest());
            final int risk_level = Ints.tryParse(riskLevel);

            member.set(Const.FIELD_RISK_TOLERANCE,risk_level).update();
            renderJson(AjaxMessage.ok(StringPool.EMPTY, Dict.dao.getRiskTolerance(risk_level)));
        } else {
            renderAjaxFailure();
        }
    }

}
